import { nextTick, useTemplateRef } from "vue"

const smoothScroll = (targetEle, targetPostiton, duration) => {
    const startPosition = targetEle.scrollTop
    const distance = targetPostiton - startPosition
    if (distance === 0) return
    let startTime = null

    const animation = (currentTime) => {
        if (startTime === null) startTime = currentTime
        const timeElapsed = currentTime - startTime
        const run = ease(timeElapsed, startPosition, distance, duration)
        targetEle.scrollTop = run
        if (timeElapsed < duration) requestAnimationFrame(animation)
    }

    const ease = (t, b, c, d) => {
        t /= d / 2
        if (t < 1) return (c / 2) * t * t + b
        t--
        return (-c / 2) * (t * (t - 2) - 1) + b
    }

    requestAnimationFrame(animation)
}

const useTableData = (tableRef, tableDataRef, initDataLine = 30, nextAppend = 50) => {
    const table = typeof tableRef === "string" ? useTemplateRef(tableRef) : tableRef
    let data = []

    const setData = (_data) => {
        // 滚动到第一行
        smoothScroll(table.value.$refs.scrollBarRef.wrapRef, 0, 500)
        data = _data
        tableDataRef.value = data.splice(0, initDataLine)
        nextTick(() => {
            const scrollDom = table.value.$refs.bodyWrapper.querySelector(".el-scrollbar__wrap")
            const rows = scrollDom.querySelectorAll(".el-table__row")
            if (rows.length < 1) return
            const rowHeight = Math.min(...[...rows].map(ele => ele.offsetHeight))
            const initLine = Math.round(scrollDom.offsetHeight / rowHeight)
            if (initLine > initDataLine && data.length > 0) {
                appendData(initLine)
            }
            table.value.$refs.scrollBarRef.update()
            const interval = setInterval(() => {
                if (!appendData(nextAppend)) {
                    clearInterval(interval)
                    table.value.$refs.scrollBarRef.update()
                }
            }, 5)
        })
    }

    const appendData = (n) => {
        const spliceData = data.splice(0, n)
        if (spliceData.length === 0) {
            return false
        }
        for (const ele of spliceData) {
            tableDataRef.value.push(ele)
        }
        table.value.$refs.scrollBarRef.update()
        return true
    }

    return setData
}

export default useTableData 